import {Login} from '@/api/login';
import cookie from 'cookie_js'
import {removeToKen, removeUserName, setToken, setUserName} from '@/utils/app'
const state = {
  isCollapse: JSON.parse(sessionStorage.getItem("isCollapse")) || false, //也可以改用localStorage ，不过需要手动清除缓存
  to_ken:'',
  username: cookie.get('username') || ''
};

const getters = {
  //类似于computed
  count: (state) => state.count + 10,
  isCollapse: state => state.isCollapse,
  username: state => state.username
};

const mutations = { 
  SET_COLLAPSE(state) {
    state.isCollapse = !state.isCollapse;

    sessionStorage.setItem("isCollapse", JSON.stringify(state.isCollapse)); //还可以用cookie_JS
  },
  SET_COUNT(state, value) {
    // state代表仓库，value是传进来的值, 外面通过  this.$state.commit('方法名',传入的值) 来调用
    state.count = value;
    console.log(state.count);
  },
  SET_TOKEN(state,value) {
    state.to_ken = value
  },
  SET_USERNAME(state,value) {
    state.username = value
  },
};

const actions = {
  login(content, requestData) {
    return new Promise((resolve, reject) => {
      //接口
      Login(requestData)
        .then((res) => {
          console.log(res);
          let data = res.data.data
          console.log(content);
          content.commit('SET_TOKEN',data.token)
          content.commit('SET_USERNAME',data.username)
          setToken(data.token)
          setUserName(data.username)
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  exit({commit}) {
    return new Promise((resolve,reject) => {
      removeToKen()
      removeUserName()
      commit('SET_TOKEN','')
      commit('SET_USERNAME','')
      resolve()
    })
    
  }
};


export default {
  namespaced:true,
  state,
  getters,
  mutations,
  actions
}
